<template>
  <div class="w-full h-[100vh] flex justify-center items-center bg-sky-950">
    <div class="login_box">
      <span class="login_title">用户名密码随意填写</span>
      <el-form class="w-full" ref="ruleFormRef" :model="form" :rules="rules" label-width="5rem">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loginLoading"
            class="w-full"
            @click="loginHandler(ruleFormRef)"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { useUserStore } from '@/stores/modules/user'
  import { type FormInstance, type FormRules } from 'element-plus'
  definePageMeta({
    title: '登录',
    hideInMenu: true
  })
  useHead({
    title: '登录'
  })
  let login: Function
  onMounted(() => {
    login = useUserStore().login
  })
  const router = useRouter()
  /** 登录表单 */
  const ruleFormRef = ref<FormInstance>()
  const form = ref({
    username: '',
    password: ''
  })
  const rules = reactive<FormRules<{ username: string; password: string }>>({
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
  })

  const loginLoading = ref(false)
  /** 点击登录按钮 */
  const loginHandler = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        const { username, password } = form.value
        loginLoading.value = true
        login({ username, password })
          .then(() => {
            router.push('/')
          })
          .catch(() => {
            form.value.password = ''
            form.value.username = ''
          })
          .finally(() => {
            loginLoading.value = false
          })
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  useKeyboardEvt(13, () => loginHandler(ruleFormRef.value))
</script>

<style scoped lang="less">
  .login_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 1.25rem;
    z-index: 999;
    width: 31.25rem;
    background-color: rgb(12 74 110);
    backdrop-filter: blur(20px); //毛玻璃属性
    border-radius: 1rem;
    overflow: hidden;

    .login_title {
      margin-bottom: 1.25rem;
      font-size: 1.875rem;
      font-weight: 700;
      background: linear-gradient(180deg, #ffffff 0%, #0e9ae9 100%);
      background-clip: text;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }

  :deep(.el-form .el-form-item__label) {
    font-size: 1rem;
    color: #fff;
  }
  :deep(.el-input) {
    height: 2rem;
  }
</style>
